class Subject {
    constructor(name) {
        this.name = name
        this.observers = []
    }

    addObserver(observer) {
        this.observers.push(observer)
    }

    removeObserver(observer) {
        const index = this.observers.findIndex(o => o.name === observer.name)
        if (index !== -1) {
            this.observers.splice(index, 1)
            console.log(observer.name, "已被", this.name, "除名");
        }
    }

    /* 触发事件 */
    trigger(msg) {
        // 通知所有观察者响应
        this.observers.forEach(ob => ob.onNotified(msg))
    }
}

class Observer {
    constructor(name, subject) {
        this.name = name
        if (subject) {
            subject.addObserver(this)
        }
    }

    /* 入圈/注册 */
    register(subject) {
        subject && subject.addObserver(this)
    }

    /* 退圈 */
    quit(subject) {
        subject.removeObserver(this)
        // return undefined
    }

    /* 响应主题发来的消息 */
    onNotified(msg) {
        console.log(this.name, "响应", msg);
    }
}

const sports = new Subject("体育")

const zl = new Observer("张龙", sports).quit(sports)
const zh = new Observer("赵虎", sports)
const mh = new Observer("马汉", sports)
console.log("zl=", zl);

setTimeout(() => {
    sports.trigger("我大伟丽表示不会家暴老公！")
}, 5000);